<?php
namespace Admin\Controller;

use Think\Controller;
use Admin\Logic\UserLogic;

class LoginController extends Controller
{
    public function index()
    {
        $this->display('login');
    }

    public function doLogin()
    {
        if (!IS_POST) {
            E('非法操作');
        }

        //获取参数
        $param = [
            'user_name' => I('post.username', null, 'htmlspecialchars'),
            'pass_word' => I('post.password', null, 'htmlspecialchars')
        ];

        //查询账号是否正确
        $user = UserLogic::verifyUserName($param['user_name']);
        if ($user === null || $user === false) {
            $this->ajaxReturn(['code' => 1, 'msg' => '用户名不存在', 'data' => null]);
        }

        //验证密码
        if ($user['pass_word'] != md5($param['pass_word'])) {
            $this->ajaxReturn(['code' => 1, 'msg' => '密码错误', 'data' => null]);
        }

        //账号被禁用
        if ($user['is_lock'] > 0) {
            $this->ajaxReturn(['code' => 1, 'msg' => '账号已被锁定，请联系管理员', 'data' => null]);
        }

        //登录成功设置Session保持登录状态
        session('user.id', $user['id']);
        session('user.user_name', $user['user_name']);
        $this->ajaxReturn(['code' => 0, 'msg' => '登录成功', 'data' => U('Index/index')]);
    }

    public function logout()
    {
        session('user.id', null);
        session('user.user_name', null);
        $this->redirect('Login/index');
    }
}